import axios from 'axios'
import { ElNotification } from 'element-plus'
// import NProgress from 'nprogress'
// import 'nprogress/nprogress.css'
import Router from '@/router/index'
import { useUserStore } from '@/stores/index'
import { requiredNumber } from 'element-plus/es/components/table-v2/src/common'

/**
 * 加载环境变量
 */
const baseURL = import.meta.env.VITE_APP_BASE_API

// NProgress.inc(0.2)
// NProgress.configure({ easing: 'ease', speed: 600, showSpinner: false })

const service = axios.create({
  baseURL,
  // adapter: require('axios/lib/adapters/http'),
  withCredentials: true,
  timeout: 20000,
})
// axios.defaults.adapter = require('axios/lib/adapters/http')
// axios.defaults.baseURL = baseURL
// axios.defaults.withCredentials = true
// axios.defaults.timeout = 10000

// service.defaults.adapter = require('axios/lib/adapters/http')
service.interceptors.request.use(
  (config) => {
    const UserStore = useUserStore()
    let token = UserStore.token
    if (token) {
      config.headers.common['Authorization'] = token
    }
    // 启动进度条
    // NProgress.start()
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    // 关闭进度条
    // NProgress.done()
    const res = response.data
    if (res.code && res.code !== 0) {
      if (res.code === 500) {
        ElNotification.error(res.msg)
      }
      return Promise.reject(service.interceptors.response)
    } else {
      return res
    }
  },
  (error) => {
    // 关闭进度条
    // NProgress.done()
    if (error.message.indexOf('timeout') != -1) {
      ElNotification.error('网络超时')
    } else {
      ElNotification.error(error.message)
    }
    return Promise.reject(error)
  }
)

export default service
// export default axios
